package com.hospital.ecard.patienthandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hospital.common.core.module.entity.ecard.*;
import com.hospital.common.core.utils.RedisUtils;
import com.hospital.common.core.utils.SpringContextHolder;
import com.hospital.ecard.cardhandler.ECardHandler;
import com.hospital.ecard.module.entity.PatientInfo;
import com.hospital.ecard.module.service.PatientInfoService;
import com.hospital.ecard.xmlutils.AuthKeySoapXmlUtils;
import com.hospital.ecard.xmlutils.SoapUtil;
import com.hospital.ecard.xmlutils.SyncCardInfoAndOperatorLogEHCSoapXmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author lvyao
 * @description 病人信息处理
 * @date 2020/7/8
 */
@Slf4j
public class PatientInfoHandler {

    private static final String RESULT_CODE = "isSuccess";
    private static final int RESULT_VALUE = 10000;
    private static final String RESULT_BUSINESS_INFO = "businessInfo";
    private static final String RESULT_MESSAGE = "errMsg";

    @Autowired
    private static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);

    @Autowired
    private static AuthKey authKey = SpringContextHolder.getBean(AuthKey.class);

    @Autowired
    private static RemoteUrl remoteUrl = SpringContextHolder.getBean(RemoteUrl.class);

    @Autowired
    private static PatientInfoService patientInfoService = SpringContextHolder.getBean(PatientInfoService.class);

    private static Object object = new Object();

    public static void updatePatientInfo(PatientInfo patientInfo, boolean isNewArrived) {
        if (patientInfo.getQrCodeText() != null) {
            boolean isUpdate = patientInfo.getQrCodeText().length() <= 85 && patientInfo.getQrCodeText().length() >= 67;
            if (!isUpdate) {
                patientInfo.setQrCodeText(null);
            }
        }
        if (patientInfo.getHealthCardId() == null) {
            //不使用之前的注册
//            CardInfo cardInfo=new CardInfo();
//            cardInfo.setKlx("3");
//            PeopleInfo peopleInfo=new PeopleInfo();
//            peopleInfo.setZjlx("01");
//            peopleInfo.setPayAccType("1");
//            peopleInfo.setAppMode("3");
//            peopleInfo.setZjhm(patientInfo.getIdNo());
//            peopleInfo.setSfzhm(patientInfo.getIdNo());
//            peopleInfo.setXm(patientInfo.getName());
//            peopleInfo.setCsrq(DateFormatUtils.format(patientInfo.getDateOfBirth(),"YYYYMMdd"));
//            String gender=patientInfo.getSex().equals("男")?"1":patientInfo.getSex().equals("女")?"2":"9";
//            peopleInfo.setXb(gender);
//            cardInfo.setPeopleInfo(peopleInfo);
//            String resVal=getPersonCardByInfo(cardInfo);
//            JSONObject jsonObject = JSON.parseObject(resVal);
//            if(jsonObject.containsKey(RESULT_CODE)){
//                int isSuccess = jsonObject.getIntValue(RESULT_CODE);
//                if(isSuccess==RESULT_VALUE){
//                    RegisterResEntity businessInfo = JSON.parseObject(jsonObject.getString(RESULT_BUSINESS_INFO), RegisterResEntity.class);
//                    patientInfo.setHealthCardId(businessInfo.getHealthCardId());
//                    patientInfo.setQrCodeText(businessInfo.getQRCode());
//                    patientInfo.setVirtualCardNum(businessInfo.getVirtualCardNum());
//                }
//            }else {
//                throw new RuntimeException(jsonObject.getString(RESULT_MESSAGE));
//            }
            //新的注册方式 20220409
            if (patientInfo.getPhoneNumberHome() == null || patientInfo.getName() ==null || patientInfo.getIdNo() == null){
                throw new RuntimeException("无电子健康卡号的患者更新信息必须填写姓名、身份证号、以及联系方式！");
            }
            EcardRegister ecardRegister = new EcardRegister();
            ecardRegister.setPhoneNum(patientInfo.getPhoneNumberHome());
            ecardRegister.setName(patientInfo.getName());
            ecardRegister.setCardType("01");
            ecardRegister.setCardNo(patientInfo.getIdNo());
            try {
                String personCardByInfoNew = ECardHandler.getPersonCardByInfoNew(JSON.toJSONString(ecardRegister), "1");
                JSONObject jsonObject = JSON.parseObject(personCardByInfoNew);
                if (!jsonObject.containsKey("virId")) {
                    throw new RuntimeException("电子健康卡注册失败返回："  + personCardByInfoNew);
                }
                patientInfo.setHealthCardId(jsonObject.getString("virId"));
                patientInfo.setVirtualCardNum(jsonObject.getString("virCardNo"));
            }catch (Exception e){
                throw new RuntimeException("电子健康卡注册失败返回值处理失败！" );
            }

            if (isNewArrived) {
                String patientId = patientInfoService.getPatientId();
                if (patientId != null) {
                    patientInfo.setPatientId(patientId);
                } else {
                    throw new RuntimeException("获取patientId失败");
                }
                patientInfoService.save(patientInfo);
            } else {
                patientInfoService.updateById(patientInfo);
            }
        }
    }

    public static String getPersonCardByInfo(CardInfo cardInfo) {
        String authKeyStr = getAuthKey();
        if (StringUtils.isEmpty(authKeyStr)) {
            throw new RuntimeException("无法获取到验证码");
        }
        StringBuffer getXmlStr = SyncCardInfoAndOperatorLogEHCSoapXmlUtils.syncCardInfoAndOperatorLogEHCSoapXml(cardInfo, authKeyStr, authKey.getOrgCode(), "syncCardInfo");
        String reVal = "";
        ResponseEntity<RegisterResEntity> returnVal = new ResponseEntity<>();
        try {
            ResultEntity resultEntity = SoapUtil.getWebReturnResult(remoteUrl.getUrl(), getXmlStr, "syncCardInfoResponse", ResultEntity.class);
            if (resultEntity.getResultCode().equals("10000")) {
                RegisterResEntity tempEntity = JSON.parseObject(resultEntity.getMessage(), RegisterResEntity.class);
                tempEntity.setImg("");
                returnVal.setErrMsg("");
                returnVal.setBusinessInfo(tempEntity);
            } else {
                returnVal.setErrMsg(resultEntity.getMessage());
            }
            returnVal.setIsSuccess(Integer.parseInt(resultEntity.getResultCode()));
        } catch (Exception ex) {
            log.error("报错信息", ex);
            returnVal.setIsSuccess(10002);
            returnVal.setErrMsg("运行中异常");
        }
        reVal = JSON.toJSONString(returnVal);
        return reVal;
    }

    public static String getAuthKey() {
        boolean authKey = RedisUtils.isExistsKey("authKey");
        String authKeyStr = RedisUtils.getKey("authKey");

        if (StringUtils.isEmpty(authKeyStr)) {
            synchronized (object.getClass()) {
                authKeyStr = RedisUtils.getKey("authKey");
                if (StringUtils.isEmpty(authKeyStr)) {
                    try {
                        AuthKeyResEntity authKeyResEntity = SoapUtil.getWebReturnResult(remoteUrl.getUrl(), AuthKeySoapXmlUtils.getAuthKeySoapXml(PatientInfoHandler.authKey, "getAuthKey"), "getAuthKeyResponse", AuthKeyResEntity.class);
                        if (authKeyResEntity != null) {
                            if (authKeyResEntity.getResultCode().equals("10000")) {
                                RedisUtils.setKey("authKey", authKeyResEntity.getAuthKey());
                                authKeyStr = authKeyResEntity.getAuthKey();
                            } else {
                                throw new RuntimeException(authKeyResEntity.getMessage());
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        return authKeyStr;
    }

}
